package com.archermind.nfc.client.transport;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import android.util.Log;

public class MinaClient {

	private static final String TAG = "MinaClient";

	private static MinaClient mInstance = new MinaClient();

	private NioSocketConnector mConnector;
	private DefaultIoFilterChainBuilder mChain;
	private MessageHandler mMessageHandler;
	private IoSession mSession;

	private MinaClient() {
	};

	public static MinaClient getInstance() {
		return mInstance;
	}

	public void startService() throws Exception {
		if (mConnector != null) {
			return;
		}

		mConnector = new NioSocketConnector();
		mChain = mConnector.getFilterChain();
		mMessageHandler = new MessageHandler();

		ObjectSerializationCodecFactory objCodecFactory = new ObjectSerializationCodecFactory();
		objCodecFactory.setDecoderMaxObjectSize(10 * 1024 * 1024);
		objCodecFactory.setEncoderMaxObjectSize(10 * 1024 * 1024);

		ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(
				objCodecFactory);

		mChain.addLast("codec", protocolCodecFilter);
		mConnector.setHandler(mMessageHandler);
		ConnectFuture cf = mConnector.connect(new InetSocketAddress(
				"192.168.42.2", 10000));

		cf.awaitUninterruptibly();

		mSession = cf.getSession();

		Log.d(TAG, "Mina client connect to server successfully");
	}

	public void stopService() {
		if (mConnector != null) {
			mConnector.dispose();
			mConnector = null;
		}

		Log.d(TAG, "Mina client disconnected from server successfully");
	}

	public IoSession getSession() {
		return mSession;
	}

	public MessageHandler getMessageHandler() {
		return mMessageHandler;
	}

}